<template>
  <view class="page">
    <view class="setup-container">
      <!-- 根据 currentStep 控制显示 设置房间 或 设置名称 -->
      <view v-if="currentStep === 'room'">
        <!-- 设置房间标题 -->
        <text class="title">设置房间</text>

        <!-- 房间选择 -->
        <view class="setup-form room-selection-container">
          <view class="room-buttons">
            <button
                v-for="(item, index) in rooms"
                :key="index"
                class="room-button"
                :class="{ 'selected-room': item.serialnum_room === selectedRoomId }"
                @click="selectRoom(item.serialnum_room)"
            >{{ item.name_room }}</button>
            <button class="create-room-button" @click="handleCreateRoom">+ 创建新房间</button>
          </view>
        </view>
      </view>

      <view v-if="currentStep === 'name'">
        <!-- 设置名称标题 -->
        <text class="title">设置名称</text>

        <!-- 名称选择 -->
        <view class="input-section">
          <input
              v-model="formData.name_equip"
              class="name-input"
              placeholder="请输入设备名称"
              @input="onDeviceNameInput"
          />
          <!-- 添加清除按钮 -->
          <text v-if="formData.name_equip" class="clear-button" @click="clearDeviceName">×</text>
        </view>
      </view>

      <!-- 统一底部导航栏 -->
      <view class="footer-nav">
        <button class="primary-btn" @click="handleNextStep">{{ currentStep === 'room' ? '下一步' : '完成设置' }}</button>
      </view>
    </view>
  </view>
</template>

<script>
import {
  _changename,
  _moveequip,
  _getsequip
} from '@/service/equip.js'
import { _addroom, _getrooms, _getRoomsNew } from '@/service/room.js'

export default {
  name: 'DeviceSetup',
  data() {
    return {
      deviceIcon: '',
      formData: {
        name_equip: '',
        serialnum_room: '',
        serialnum_sequip: '',
        serialnum_fequip: '',
        notes: '',
        serialnum_equip: '',
        macAddress: '',
      },
      rules: {
        name_equip: {
          rules: [{
            required: true,
            errorMessage: '请输入设备名称'
          }]
        },
        serialnum_room: {
          rules: [{
            required: true,
            errorMessage: '请选择房间'
          }]
        }
      },
      firstCategories: [],
      secondCategories: [],
      rooms: [],
      currentUser: '',
      statusBarHeight: 0,
      // 新增房间相关数据
      isAddingRoom: false,  // 是否正在添加房间
      newRoomName: '',       // 新房间名称
      currentStep: 'room',   // 当前步骤：'room' -> 房间设置, 'name' -> 名称设置
      selectedRoomId: ''     // 已选房间ID
    }
  },
  async onLoad(options) {
    if (options.serialnum_equip) {
      this.formData.serialnum_equip = options.serialnum_equip;
    }
    if (options.macAddress) {
      this.formData.macAddress = options.macAddress;
    }

    const userInfo = uni.getStorageSync('userInfo');
    if (userInfo) {
      console.log('页面加载时获取到用户信息:', userInfo);
      this.currentUser = userInfo.accountNum;
    }

    this.getrooms().then(res => {
      console.log('获取到的房间信息:', this.rooms);
    });

    uni.getSystemInfo({
      success: (res) => {
        this.statusBarHeight = res.statusBarHeight;
      }
    });
  },
  methods: {
    async getrooms() {
      try {
        let data = {
          account_user: this.currentUser
        }
        let res = await _getrooms(data);
        console.log(res);
        this.rooms = res.data || [];
        console.log('获取到的房间信息:', this.rooms);
        
        // 如果有已选房间ID，保持选择状态
        if (this.formData.serialnum_room) {
          this.selectedRoomId = this.formData.serialnum_room;
        }
      } catch (e) {
        console.log(e)
      }
    },
    async handleSubmit() {
      try {
        console.log('开始提交设备设置...');

        if (this.rooms.length === 0) {
          console.log('错误：用户没有可用房间');
          uni.showToast({
            title: '请先创建房间再添加设备',
            icon: 'none'
          });
          return;
        }

        uni.showLoading({
          title: '保存中'
        });

        console.log('准备初始化设备...');

        console.log('准备设置设备名称:', this.formData.name_equip);
        // 设置设备名称
        const nameResult = await _changename({
          serialnum_equip: this.formData.serialnum_equip,
          name_equip: this.formData.name_equip
        });

        if (!nameResult.flag || nameResult.status !== 200) {
          throw new Error(nameResult.message || '设备名称设置失败');
        }

        console.log('准备设置设备房间:', this.formData.serialnum_room);
        // 设置设备房间
        const roomResult = await _moveequip({
          cbindinguseraccount_equip: this.currentUser,
          serialnum_equip: this.formData.serialnum_equip,
          serialnum_room: this.formData.serialnum_room
        });

        if (!roomResult.flag || roomResult.status !== 200) {
          throw new Error(roomResult.message || '设备房间设置失败');
        }

        console.log('设备设置成功');
        uni.hideLoading();
        uni.showToast({
          title: '设备设置成功',
          icon: 'success'
        });

        setTimeout(() => {
          uni.reLaunch({
            url: '/pages/index1/index1'
          });
        }, 1500);

      } catch (err) {
        uni.hideLoading();
        console.error('保存设备信息失败:', err);
        uni.showToast({
          title: err.message || '保存失败，请重试',
          icon: 'none'
        });
      }
    },

    handleCancel() {
      console.log('取消设备设置操作');
      uni.showModal({
        title: '提示',
        content: '确定要取消设备设置吗？',
        success: (res) => {
          if (res.confirm) {
            console.log('用户确认取消操作');
            uni.navigateBack();
          }
        }
      });
    },

    handleNextStep() {
      console.log('下一步按钮被点击');

      if (this.currentStep === 'room') {
        // 验证是否选择了房间
        if (this.formData.serialnum_room === '') {
          console.warn('警告：未选择房间');
          uni.showToast({
            title: '请选择房间',
            icon: 'none'
          });
          return;
        }

        // 切换到名称设置步骤
        this.currentStep = 'name';
      } else if (this.currentStep === 'name') {
        // 验证设备名称
        if (!this.formData.name_equip) {
          console.warn('警告：未输入设备名称');
          uni.showToast({
            title: '请输入设备名称',
            icon: 'none'
          });
          return;
        }

        // 提交设备设置
        this.handleSubmit();
      }
    },

    // 房间相关方法
    handleCreateRoom() {
      console.log('创建新房间按钮被点击');
      uni.navigateTo({
        url: '/pages/roomadd/roomadd',
        success: () => {
          console.log('跳转到添加房间页面');
        },
        fail: (err) => {
          console.error('页面跳转失败:', err);
          uni.showToast({
            title: '跳转失败',
            icon: 'none'
          });
        }
      });
    },

    selectRoom(serialnum_room) {
      console.log('选择房间:', serialnum_room);
      this.formData.serialnum_room = serialnum_room;
      this.selectedRoomId = serialnum_room; // 更新选中房间ID
    },

    onDeviceNameInput(value) {
      console.log('设备名称输入:', value);
    },

    clearDeviceName() {
      console.log('清除设备名称');
      this.formData.name_equip = '';
    }
  },
  async onShow() {
    console.log('页面显示，刷新房间列表');
    await this.getrooms();
    
    // // 检查是否有新创建的房间需要自动选择
    // const newRoomId = uni.getStorageSync('newRoomId');
    // if (newRoomId) {
    //   console.log('检测到新创建的房间ID:', newRoomId);
    //   uni.removeStorageSync('newRoomId'); // 清除存储的新房间ID
    //
    //   // 查找新创建的房间
    //   const newRoom = this.rooms.find(room => room.value === newRoomId);
    //   if (newRoom) {
    //     console.log('自动选择新创建的房间:', newRoom);
    //     this.formData.serialnum_room = newRoom.value;
    //   } else {
    //     console.warn('未找到新创建的房间');
    //   }
    // }
  }
}
</script>

<style scoped>
/* 添加新的样式 */
.setup-container {
  margin: 20px; /* 添加外边距 */
  margin-top: 100rpx;
}

.input-section {
  position: relative;
  background-color: #e6e6e6; /* 输入框背景色 */
  border-radius: 12px;
  padding: 10px 40px 10px 10px; /* 内边距 */
  margin-bottom: 20px;
  margin-top: 20px;
}

.name-input {
  width: 100%;
  height: 40px;
  font-size: 16px;
  color: #333;
  border: none;
  background-color: transparent;
  outline: none;
}

.clear-button {
  position: absolute;
  top: 50%;
  right: 10px;
  transform: translateY(-50%);
  font-size: 16px;
  color: #999;
  cursor: pointer;
}

.room-selection-container {
  display: flex;
  justify-content: center;
}

.room-buttons {
  display: flex;
  flex-wrap: wrap;
  justify-content: flex-start; /* 按钮左对齐 */
  width: 100%;
  margin-top: 20px; /* 增加顶部间距 */
}

.room-button {
  margin: 5px;
  padding: 10px 20px;
  border-radius: 12px;
  background-color: #f5f5f5;
  color: #666;
  font-size: 14px;
  border: none;
  cursor: pointer;
  min-width: 80px; /* 设置最小宽度 */
  height: 40px; /* 统一按钮高度 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.room-button.selected-room {
  background-color: #1890ff;
  color: #fff;
}

.create-room-button {
  margin: 5px;
  padding: 10px 20px;
  border-radius: 12px;
  background-color: #e6f7ff;
  color: #1890ff;
  font-size: 14px;
  border: none;
  cursor: pointer;
  min-width: 80px; /* 设置最小宽度 */
  height: 40px; /* 统一按钮高度 */
  display: flex;
  align-items: center;
  justify-content: center;
}

.title {
  font-size: 24px; /* 调整标题字体大小 */
  color: #333; /* 调整标题颜色 */
  margin-bottom: 20px; /* 增加底部间距 */
}

/* 新增底部导航栏样式 */
.footer-nav {
  position: fixed;
  bottom: 0;
  left: 0;
  width: 100%;
  background-color: #fff;
  //box-shadow: 0 -2px 4px rgba(0, 0, 0, 0.1);
  padding: 10px 0;
  display: flex;
  justify-content: center;
}

.primary-btn {
  width: 80%;
  height: 40px;
  background-color: #e6f7ff;
  color: #1890ff;
  border: none;
  border-radius: 20px;
  font-size: 16px;
}
</style>

